<?php
/**
 * Created by PhpStorm.
 * User:王加明
 * Date: 2017-04-13
 * Time: 下午 1:40
 */
namespace app\hongyanche\model;
use think\Db;
use think\exception\ErrorException;
use think\Paginator;
use think\Model;
class Maintain extends Model{
    private $userId;
    private $auth;
    private $admin;
    private $config;
    private $key = '837f373a-23ac-4607-a2f5-b029084841af';
    function __construct()
    {
        //检查权限
        $this->admin = model('admin');
        $auth = $this->admin -> is('maintain');
        if($auth['state']){
            $this->auth = $auth['state'];
        }
        //获取user_id
        if (is_null($this->userId)) {
            $user_id = model('user');
            $userId = $this->userId = $user_id->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }

    }

    //创建label
    public function label_add($cn)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if($cn) return ['state'=>0,'errormsg'=>'请输入类别'];
        $data['cn'] = $cn;
        $data['state'] = 2;
        $res = \db('maintain_admin_label')->insertGetId($data);
        if(!$res) return ['state'=>0,'errormsg'=>'创建失败,请重试'];
        $res = \db('maintain_admin_label')->where("label_id = $res")->update(['cn_code'=>'0'.$res]);
        if(!$res) return ['state'=>0,'errormsg'=>'创建失败'];
        model('action')->add('创建站点类别','类别名',$cn);
        return ['state'=>1,'errormsg'=>'成功'];
    }

    public function label_rename($label_id,$newname)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择类别'];
        if(!$newname) return ['state'=>0,'errormsg'=>'请输入标签名'];
        $data['cn'] = $newname;
        $res = \db('maintain_admin_label')->where("label_id = $label_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
        model('action')->add('修改站点类别名','类别名',$newname);
        return ['state'=>1,'errormsg'=>'成功'];
    }

    public function label_remove($label_id)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择类别'];
        $res = \db('maintain_admin_label')->where("label_id = $label_id")->update(['state'=>0]);
        if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
        $name = \db('maintain_admin_label')->where("label_id = $label_id")->find();
        model('action')->add('删除站点类别','类别名',$name['cn']);
        return ['state'=>1,'errormsg'=>'成功'];
    }

    public function label_list()
    {
        $label = \db('maintain_admin_label')->where('state = 1')->select();
        foreach ($label as $k =>$v){
            if($v['cn_code'] == '04'){
                $list = $label[$k];
                unset($label[$k]);
            }
        }
        if(isset($list)){
            array_unshift($label,$list);
        }
        if(!$label) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['list'=>$label]];
    }

    public function add($data)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$data['cust_code']) return ['state'=>0,'errormsg'=>'请输入站点编号'];
        if(!$data['cust_name']) return ['state'=>0,'errormsg'=>'请输入站点名称'];
        if(!$data['company_tel']) return ['state'=>0,'errormsg'=>'请输入联系电话'];
//        if(!$data['lng']) return ['state'=>0,'errormsg'=>'请输入经度'];
//        if(!$data['lat']) return ['state'=>0,'errormsg'=>'请输入纬度'];
        if(!$data['province']) return ['state'=>0,'errormsg'=>'请输入省'];
        if(!$data['city']) return ['state'=>0,'errormsg'=>'请输入市'];
        if(!$data['area']) return ['state'=>0,'errormsg'=>'请输入区'];
        if(!$data['company_address']) return ['state'=>0,'errormsg'=>'请输入详细地址'];
//        if(!$data['cust_type']) return ['state'=>0,'errormsg'=>'请选择类别'];
        $data['state'] = 2;
        $data['create_time'] = time();
        $data['cust_type'] = '08';
        //判断客户编号是否存在
        $info = \db('maintain_pj_cust')->where("cust_code = '$data[cust_code]'")->find();
        if($info) return ['state'=>0,'errormsg'=>'客户编号已存在'];
        $res = \db('maintain_pj_cust')->insert($data);
        if(!$res) return ['state'=>0,'errormsg'=>'添加失败,请重试'];
        model('action')->add('添加站点','站点名',$data['cust_name']);
        return ['state'=>1,'errormsg'=>'添加成功'];
    }

    public function modify($cust_code,$data)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$cust_code) return ['state'=>0,'errormsg'=>'请输入站点编号'];
        //判断站点是否为落地服务
        $luodi = \db('maintain_pj_cust')->where("cust_code = '$cust_code' and cust_type = '08'")->find();
        if($luodi){
            if(!$data['cust_code']) return ['state'=>0,'errormsg'=>'请输入站点编号'];
            if(!$data['cust_name']) return ['state'=>0,'errormsg'=>'请输入站点名称'];
            if(!$data['company_tel']) return ['state'=>0,'errormsg'=>'请输入联系电话'];
            if(!$data['province']) return ['state'=>0,'errormsg'=>'请输入省'];
            if(!$data['city']) return ['state'=>0,'errormsg'=>'请输入市'];
            if(!$data['area']) return ['state'=>0,'errormsg'=>'请输入区'];
            if(!$data['company_address']) return ['state'=>0,'errormsg'=>'请输入详细地址'];
            $a = $data;
        }else {
//            if (!$data['lng']) return ['state' => 0, 'errormsg' => '请输入经纬度'];
//            if (!$data['lat']) return ['state' => 0, 'errormsg' => '请输入纬度'];
//            $a['lng'] = $data['lng'];
//            $a['lat'] = $data['lat'];
            if(strpos($data['lant'],',') ===false){
                return ['state'=>0,'errormsg'=>'经纬度错误'];
            }
            $a['lng'] = explode(',',$data['lant'])[0];
            $a['lat'] = explode(',',$data['lant'])[1];
        }
        $res = db('maintain_pj_cust')->where("cust_code = '$cust_code'")->update($a);
        if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
        model('action')->add('修改站点','站点名',$data['cust_name']);
        return ['state'=>1,'errormsg'=>'修改成功'];
    }

    public function release($cust_code,$release)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$cust_code) return ['state'=>0,'errormsg'=>'请选择站点'];
        if($release){
            $data['state'] = 1;
        }else{
            $data['state'] = 2;
        }
        $res = \db('maintain_pj_cust')->where("cust_code = '$cust_code'")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'失败'];
        $res = \db('maintain_pj_cust')->where("cust_code = '$cust_code'")->find($data);
        if($release) {
            model('action')->add('开放站点', '站点名', $res['cust_name']);
        }else{
            model('action')->add('关闭站点', '站点名', $res['cust_name']);
        }
        return ['state'=>1,'errormsg'=>'成功'];
    }

    public function remove($cust_code)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$cust_code) return ['state'=>0,'errormsg'=>'请选择要删除的站点'];
        $data['state'] = 0;
        $res = \db('maintain_pj_cust')->where("cust_code = '$cust_code'")->update($data);
        if(!$res) return ['state'=>0,'errormnsg'=>'删除失败'];
        $name = db('maintain_pj_cust')->where("cust_code = '$cust_code'")->find();
        model('action')->add('删除站点', '站点名', $name['cust_name']);
        return ['state'=>1,'errormsg'=>'删除成功'];

    }

    public function maintain_list($filter)
    {
        if($filter['page']){
            $page = $filter['page'];
        }else{
            $page = 1;
        }
        $where = 'c.state != 0 and l.state = 1';
        if($filter['keywords']){
            $where .= " and cust_code like '%$filter[keywords]%' or cust_name like '%$filter[keywords]%'";
        }
        $maintain = db('maintain_pj_cust')->alias('c')
            ->field('cust_code,cust_name,cn,label_id,c.state,company_tel,company_address,cust_type')
            ->join('maintain_admin_label l','c.cust_type = l.cn_code')
            ->where($where)->paginate(12,false,['page'=>$page]);
        $pages = $maintain->render();
        $maintain = $maintain->items();
        $pages=preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$pages);
        $pages=str_replace("&laquo;","上一页",$pages);
        $pages=str_replace("&raquo;","下一页",$pages);
        if(!$maintain) return ['state'=>1,'data'=>[]];
        //查询标签
        foreach ($maintain as $k =>$v){
            if($v['cust_type'] == '08'){
                $maintain[$k]['l'] = 'luodi';
            }
            if($v['state'] == 1){
                $maintain[$k]['released']  = 1;
            }else{
                $maintain[$k]['released']  = 0;
            }
            unset($maintain[$k]['state']);
        }
        return ['state'=>1,'data'=>['list'=>$maintain],'page'=>$pages];
    }
    //获取站点信息
    public function getinfo($cust_code)
    {
        if(!$cust_code) return ['state'=>0,'errormsg'=>'请选择站点'];
        $info = \db('maintain_pj_cust')->where("cust_code = '$cust_code' and state != 0")->find();
        if($info['cust_type'] == '08'){
            $info['l'] = 'luodi';
        }
        if($info['lng'] && $info['lat']){
            $info['lant'] = $info['lng'].','.$info['lat'];
        }else{
            $info['lant'] = '';
        }
        if(!$info) return ['state'=>0,'errormsg'=>'未找到该站点'];
        return ['state'=>1,'data'=>['info'=>$info]];
    }
    //用户获取站点列表
    public function station_list($filter)
    {
        if(!$filter['cust_type']) return ['state'=>0,'errormsg'=>'请选择类别'];
        if(!$filter['province']){
            $res = \db('maintain_pj_cust')->field('cust_name,company_tel,company_address,cust_code,lng,lat')->where("state = 1 and cust_type = '$filter[cust_type]' and (province like '%安徽%' or company_address like '%安徽省%')")->select();
            if(!$res) return ['state'=>1,'data'=>[]];
            return ['state'=>1,'data'=>['list'=>$res]];
        }
        $where = "state = 1 and cust_type = '$filter[cust_type]'";
        if($filter['province']){
            $where .= " and province like '%$filter[province]%'";
        }
        if($filter['city']){
            $where .= " and city like '%$filter[city]%'";
        }
        if($filter['area']){
            $where .= " and city like '%$filter[area]%'";
        }
        $res = db('maintain_pj_cust')->field('cust_name,company_tel,company_address,cust_code,cust_type,lng,lat')->where($where)->select();
        if(!$res) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['list'=>$res]];
    }
    /*//被动获取服务站信息
    function getServiceStation(){
        $api = new Maintain_api();
        $data = $api->getServiceInfo();
        if($data){
            return [
                'state'=>1,
                'data'=>$data
            ];
        }
        return [
            'state'=>0,
            'errormsg'=>'Parameter error'
        ];
    }*/
    //被动获取服务详情
    function getServiceInfo(){}
    //获取服务类型
    function service_type(){
        $type = getConfig('maintain');
        $list =[];
        $i = 0;
        foreach($type as $k=>$v){
            $list[$i]['type_id'] = $v['id'];
            $list[$i]['type_name'] = $v['title'];
            $i++;
        }
        return array('state'=>1,'list'=>$list);
    }
    /*//被动获取车联网实销数据
     function car_sale(){
         $maintain = new Maintain_api;
         $info =  $maintain->car_sale();
         return $info;
     }*/
    //被动获取用户在SIH取消的预约数据
    function apply_state(){}
    /*//被动获取SIH歘过来的数据数据
    function user_info(){}*/

    /*//被动接收客户信息
    function hy_userInfo($_REQUEST){
        $maintain = new Maintain_api;
        $info =  $maintain->hy_userInfo($_REQUEST);
        if($info){
            //将数据进行转换
        }
    }*/
    //定时器
    function timer(){
        $statr = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/_hongyanche/switch.txt');
        if(!$statr){
            die();
        }
        $interval=60; // 每隔5分钟运行
        //业务逻辑
        $where = "a.motastate = 1";
        $car_sala = Db::name('maintain_zvehicle')
            ->alias('a')
            ->join('maintain_customer b','a.vin = b.vin')
            ->field('a.vin,a.zdchgr,b.user_id')
            ->where($where)
            ->select();
        $data = "";
        if(!$car_sala){
            die();
        }
        foreach($car_sala as $k=>$v){
            $user_id[] =$v['user_id'];
            $data['time'][$v['user_id']] = $v['zdchgr'];
            $data['value'][$v['user_id']]= "你的车辆强保将于".$v['zdchgr']."到期，请你及时进行强保";
        }
        $data['title'] = "通知";
        $user = implode(',',$user_id);
        $res = model('message')->send("weyard",$data,$user);
        /*$fp = fopen('test.txt','a');
        fwrite($fp,"3\r\n");
        fclose($fp);*/
        sleep($interval); // 等待5分钟
        $this->timer();
    }
    /**
     * 计算两点地理坐标之间的距离
     * @param  Decimal $lng1 起点经度
     * @param  Decimal $lat1  起点纬度
     * @param  Decimal $lng2 终点经度
     * @param  Decimal $lat2  终点纬度
     * @param  Int     $unit       单位 1:米 2:公里
     * @param  Int     $decimal    精度 保留小数位数
     * @return Decimal
     */
    function getDistance($lng1, $lat1, $lng2, $lat2, $unit=2, $decimal=2){

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $lat1 * $PI / 180.0;
        $radLat2 = $lat2 * $PI / 180.0;

        $radLng1 = $lng1 * $PI / 180.0;
        $radLng2 = $lng2 * $PI /180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if($unit==2){
            $distance = $distance / 1000;
        }
        return round($distance, $decimal);
    }

    //获取用户当前位置信息
//    function station_list($data){
//        if(!isset($data['lng']) && !$data['lng']){
//            return array('state'=>0,'errormsg'=>'error lng');//经度
//        }
//        if(!isset($data['lat'] ) && !$data['lat']){
//            return array('state'=>0,'errormsg'=>'error lat');//纬度
//        }
//        if (isset($data['page']) && $data['page'] != '') {
//            $page = $data['page'] - 1;
//        } else {
//            $page = 0;
//        }
//        if (isset($data['maxPerPage']) && $data['maxPerPage'] != '') {
//            $maxPerPage = $data['maxPerPage'];
//        } else {
//            $maxPerPage = 12;
//        }
//        $lng1  = $data['lng'];
//        $lat1   = $data['lat'];
//        $PI = 3.1415926;
//        $EARTH_RADIUS = 6370.996;
//        if($data['cust_type']){
//            $where = "lng!=0 and lat!=0 and cust_type = $data[cust_type]";
//        }else{
//            $where = "lng!=0 and lat!=0";
//        }
//        $order =  "(2 * asin(sqrt(pow(sin((ci_lng-$lng1)*$PI/180/2),2) + cos($lat1 * $PI / 180.0) * cos(ci_lat*$PI / 180.0) * pow(sin((ci_lat-$lat1)*$PI/180/2),2))))*$EARTH_RADIUS asc";
//        $list = Db::name('maintain_pj_cust')
//                ->field('*,(2 * asin(sqrt(pow(sin((ci_lng-'.$lng1.')*'.$PI.'/180/2),2) + cos('.$lat1 * $PI .'/ 180.0) * cos(ci_lat*'.$PI.' / 180.0) * pow(sin((ci_lat-'.$lat1.')*'.$PI.'/180/2),2))))*'.$EARTH_RADIUS.' as distance ')
//                ->where($where)
//                ->order($order)
//                ->limit($page * $maxPerPage, $maxPerPage)
//                ->select();
//        foreach ($list as $k=>$v){
//           $list[$k]['distance'] = round($list[$k]['distance'],2);
//        }
//        if(!$list){
//            return array('state'=>0,'errormsg'=>'Parameter error');
//        }
//        return array('state'=>1,'data'=>['list'=>$list]);
//    }
    //获取单条信息
    function Info($apply_id){
        if(!$apply_id){
            return [
                'state'=>0,
                'errormsg'=>'Parameter error'
            ];
        }
        $where = "appointe_id=$apply_id";
        $info = Db::name()->where($where)->find();
        if(!$info){
            return [
                'state'=>0,
                'errormsg'=>'Parameter error'
            ];
        }
        return $info;
    }
    //获取用户信息
    private function userInfo($user_id=null){
        if($user_id == null){
            $user_id = $this->userId;
        }else{
            $user_id  = $user_id;
        }
        $userInfo = $this->admin->getInfoById($user_id);
        if($userInfo){
            return $userInfo;
        }
        return;
    }
    //预约车辆的驾驶人员信息
    function customer_info(){
        $user_id = $this->userId;
        if(!$user_id){
            return array('state'=>0,'errormsg'=>'please login');
        }
        //在用户id
        $where = "user_id = $user_id";
        $info = Db::name('maintain_customer')->where($where)->find();
        if($info){
            return array('state'=>1,'data'=>['info'=>$info]);
        }
        //手机查询
        $where = "user_id = $user_id and state = 1";
        $tel = Db::name('user_tel')->filed('tel')->where($where)->find();
        if(!$tel){
            return array('state'=>0,'errormsg'=>'Please bind phone number');
        }
        $where = "pnum = $tel";
        $info = Db::name('maintain_customer')->where($where)->find();
        if($info){
            $data['user_id'] = $user_id;
            Db::name('maintain_customer')->where($where)->update($data);
            return array('state'=>1,'data'=>['info'=>$info]);
        }
        return array('state'=>0,'errormsg'=>'not find');

    }



    //预约申请创建
    function reserve_create($data){
        $user_id = $this->userId;
        $data['state'] = 3;//编辑中
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['user_id'] = $user_id;
        $data['apply_time'] = strtotime($data['apply_time']);
        if(!$data['customer_id']) return ['state'=>0,'errormsg'=>'请选择车辆'];
        if(!$data['ci_code']) return ['state'=>0,'errormsg'=>'请选择服务站'];
        if(!$data['type']) return ['state'=>0,'errormsg'=>'请选择服务类型'];
        if(!$data['apply_time']) return ['state'=>0,'errormsg'=>'请选择预约时间'];
        if($data['apply_time']<strtotime("+7 days")){
            return ['state'=>0,'errormsg'=>'预约时间必须大于等于7天'];
        }
        //判断车辆是否是红岩车
        $vin = db('maintain_customer')->alias('c')->join('maintain_zvehicle z','c.vin = z.vhvin')->where("customer_id = $data[customer_id] and c.state = 1")->find();
        if($data['type'] !=3){
            if(!$vin){
                return ['state'=>0,'errormsg'=>'您的车不能选择保养'];
            }
        }
        $res= Db::name('maintain_apply')->insertGetId($data);
        if($res){
            return array('state'=>1,'errormsg'=>'create success');
        }
        return array('state'=>0,'errormsg'=>'create false');
    }
    //用户获取申请记录
    function reserve_list($filter){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        if (isset($filter['page']) && $filter['page'] != '') {
            $page = $filter['page'] - 1;
        } else {
            $page = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        $where = "a.user_id = $this->userId";
        $list  = Db::name('maintain_apply')
            ->alias('a')
            ->join('maintain_customer b','a.customer_id = b.customer_id')
            ->field('a.*,b.vin')
            ->where($where)
            ->limit($page * $maxPerPage, $maxPerPage)
            ->select();
        $class = getConfig('maintain');
        foreach($list as $k=>$v){
            if($v['vin']){
                $where ="vin=".$v['vin'];
                $car_name = Db::name('maintain_zvehicle')->field('zsdcmc')->where($where)->find();
                if($car_name){
                    $list[$k]['car_name'] = $car_name['zsdcmc'];
                }
            }
            foreach($class as $kk=>$vv){
                if($v['type'] == $vv['id']){
                    $list[$k]['types'] = $vv['title'];
                }
            }
        }
        if(!$list){
            return array('state'=>0,'errormsg'=>'not find apply');
        }
        return array('state'=>1,'data'=>['list'=>$list]);
    }
    //预约申请
    function reserve_apply($apply_id){
        if(!$apply_id){
            return [
                'state'=>0,
                'errormsg'=>"apply_id  error"
            ];
        }
        $where = "a.apply_id=$apply_id";
        //$info = Db::name('maintain_apply')->where($where)->find();
        $info = Db::name('maintain_apply')
            ->alias('a')
            ->join('maintain_customer b','a.customer_id = b.customer_id')
            ->where($where)
            ->find();
        if(!$info){
            return[
                'state'=>0,
                'errormsg'=>'Parameter error'
            ];
        }
        $demand = "qiangbao";
        $config = getConfig('maintain')[$demand]['id'];
        //判断预约服务
        if($info['type']){
            $class = explode(",",$info['type']);
        }else{
            return array('state'=>0,'errormsg'=>'Please select service');
        }
        //判断是否提交车辆信息
        if($info['customer_id']){
            $car = explode(",",$info['customer_id']);
        }else{
            return array('state'=>0,'errormsg'=>'Please select car');
        }
        //检查预约车辆是否强保
        foreach ($class as $k=>$v){
            if($v == $config){
                foreach($car as $kk=>$vv){
                    $where = "car_id=$vv";
                    $res = Db::name('maintain_zvehicle')->where($where)->find();
                    if($res){
                        if($res['motastate']==1){
                            return [
                                'state'=>0,
                                'errormsg'=>$res['zsdcmc']." already qiangbao"
                            ];
                        }
                        $info['type'] = 'A';
                    }
                }
            }
        }
        //获取预约token
        //$code = $this->code($apply_id);
        //$info['code'] = $code;
        //将数据传给SIH加入传如成功

        $data['apply_time'] = $_SERVER['REQUEST_TIME'];
        $data['state']       = 2;
        $where = "apply_id=$apply_id";
        $res = Db::name('maintain_apply')->where($where)->update($data);
        /* //路劲走配置文件
         $demand = "apply";
         $url = getConfig('maintain_api')[$demand]['url'];
         //调用接口向sih传送数据
         $maintain = new Maintain_api;
         $info = json_encode($info);//转换成json格式
         $a = $maintain->send($url,$type="post",$res="json",$info);
         dump($a);
         //注意查看$a数据类型*/


    }
    //取消预约
    function reserve_cancel($apply_id){
        $data['state'] = 0;
        $where = "apply_id=$apply_id";
        $res = Db::name('maintain_apply')->where($where)->update($data);
        if($res){
            //向车联网传送预约状态

            return [
                'state'=>1,
                'errormsg'=>'cancel success'
            ];
        }
        return [
            'state'=>0,
            'errormsg'=>'cancel false'
        ];
    }
    /* //预约编辑
     function reserve_modify($key,$content,$apply_id=null){
         if($apply_id == null){
             $apply_id = $this->reserve_create();
         }else{
             $apply_id = $apply_id;
             $where = "apply_id=$apply_id";
             $result = Db::name("maintain_apply")->field('state')->where($where)->find();
             if($result['state'] == 2){
                 return [
                     'state'=>0,
                     'errormsg'=>"appling......"
                 ];
             }
         }
         //判断是时间是否符合要求
         $time = time();
         if($key == "apply_time"){
             if($content-$time<604800){
                 return [
                     'state'=>0,
                     'errormsg'=>'Please choose seven days later'
                 ];
             }
         }
         $data[$key] = $content;
         $where = "apply_id=$apply_id and state=3";
         $res = Db::name('maintain_apply')->where($where)->update($data);
         if($res){
             return [
                 'state'=>1,
                 'errormsg'=>'edite success'
             ];
         }
         return [
             'state'=>0,
             'errormsg'=>'edite false'
         ];
     }*/



    //获取验证 token
    function code($apply_id){
        if(empty($apply_id)){
            return [
                'state' => 0,
                'errormsg' => ' Parameter error'
            ];
        }
        //获取配置文件token参数
        $demand = "maintain_apply";
        $token = model('Token');
        $data['content'] = $apply_id;
        $token = $token->add($demand,$data);
        if(!$token['state']){
            return json($token);
        }
        foreach($token as $k=>$v){
            $code = $v['code'];
        }
        return $code;
    }

    //创建评价
    function comment_create($unit_id = null,$pid=null){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        if($unit_id){
            $data['unit_id'] = $unit_id;
        }
        //判断是回复还是发起评价
        if($pid){
            $data['pid'] = $pid;
        }else{
            $data['pid'] = 0;
        }
        $data = [
            'state'=>1,
            'create_time'=>$_SERVER['REQUEST_TIME'],
            'user_id'     =>$this->userId
        ];
        $res = Db::name('maintain_comment')->insert($data);
        if(!$res){
            return array('state'=>0,'errormsg'=>'comment create false');
        }
        $where = "user_id=".$this->userId."and state=1";
        $order = "create_time desc";
        $result = Db::name('maintain_comment')->field('comment_id')->where($where)->order($order)->find();
        if(!$result){
            return array('state'=>0,'errormsg'=>'not comment');
        }
        return $result['comment_id'];
    }
    //编辑评价
    function comment_edit($data){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        //判断参数是否存在
        if(!isset($data['unit_id']) && $data['unit_id']==''){
            return array('state'=>0,'errormsg'=>'please enter unit_id');
        }
        if(!isset($data['content']) && $data['content']==''){
            return array('state'=>0,'errormsg'=>'please enter comment');
        }
        if(!isset($data['comment_id']) && $data['comment_id']==''){
            return array('state'=>0,'errormsg'=>'please enter comment_id');
        }
        $where = "comment_id=$data[comment_id]";
        $res = Db::name('maintain_comment')->where($where)->insert($data);
        if($res){
            return array('state'=>1,'errormsg'=>'comment success');
        }
        return array('state'=>0,'errormsg'=>'comment false');

    }
    //删除评价
    function comment_remove($comment_id){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        if(!$comment_id){
            return array('state'=>0,'errormsg'=>'please enter comment_id');
        }
        //管理员可以随意删除评价
        if($this->auth){
            $where  = "comment_id = $comment_id";
        }else{
            //用户只能删除自己的
            $where  = "comment_id = $comment_id and user_id = $this->userId";
        }
        $data = [
            'state'=>0
        ];
        $res = Db::name('maintain_comment')->where($where)->update($data);
        if($res){
            return array('state'=>1,'errormsg'=>'comment remove success');
        }
        return array('state'=>0,'errormsg'=>'comment remove false');
    }
    //评价列表
    function comment_list($filter){
        if (isset($filter['page']) && $filter['page'] != '') {
            $page = $filter['page'] - 1;
        } else {
            $page = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        if (isset($filter['unit_id']) && $filter['unit_id'] != '') {
            return array('state'=>0,'errormsg'=>'please enter unit_id');
        }
        $where = "state = 1 and unit_id = $filter[unit_id]";
        $list = Db::name('maintain_comment')->where($where)->limit($page*$maxPerPage,$page)->select();
        if($list){
            return array('state'=>1,'data'=>['list'=>$list]);
        }
        return array('state'=>0,'errormsg'=>'not find comment');
    }



    //用户车辆列表
    function vehicle_list($filter){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'请登录');
        }
        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'];
        } else {
            $pages = 1;
        }
        //用户端查询
        $tel = db('user_tel')->where("user_id = $this->userId")->find()['tel'];
        if(!$tel){
            $where = "user_id=$this->userId";
        }else{
            $where = "(pnum = $tel) or (user_id = $this->userId) ";
        }
        if(isset($filter['admin'])) {
            $where2 = 'state !=0';
        }else{
            $where2 = 'state = 1';
        }
        if($filter['keywords']){
            $where2 .= " and (vin like '%$filter[keywords]%' or pnum = '$filter[keywords]')";
        }
        $order = "state desc,create_time desc";
        $list = Db::name('maintain_customer')
            ->where($where)
            ->where($where2)
            ->order($order)
            ->paginate(12,false,['page'=>$pages]);
        $page = $list->render();
        $list = $list->items();
        $page=preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page2($1,1);'>$2</a>",$page);
        $page=str_replace("&laquo;","上一页",$page);
        $page=str_replace("&raquo;","下一页",$page);
        if(!$list){
            return [
                'state'=>1,
                'data'=>[],
                'page'=>$page
            ];
        }

        return [
            'state'=>1,
            'data'=>['list'=>$list],
            'page'=>$page
        ];
    }
    //创建新车辆信息
    function vehicle_create($data){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        if(!$data['vin']){
            return array('state'=>0,'errormsg'=>'请输入vin号');
        }
        if(!$data['uname']){
            return array('state'=>0,'errormsg'=>'请输入驾驶人员姓名');
        }
        if(!$data['role']){
            return array('state'=>0,'errormsg'=>'请选择角色');
        }
        if(!preg_match('/^([\xe4-\xe9][\x80-\xbf]{2}){2,4}$/',$data['uname'])){
            return array('state'=>0,'errormsg'=>'姓名有误,请重新输入');
        }
        if(!$data['vehicle_license_province']){
            return array('state'=>0,'errormsg'=>'请输入车辆所属地');
        }
        if(!$data['vehicle_license_number']){
            return array('state'=>0,'errormsg'=>'请输入车牌号');
        }
        if (!preg_match("/[A-Z][A-Z_0-9]{5}$/", $data['vehicle_license_number'])) {
            return array('state'=>0,'errormsg'=>'车牌号有误,请重新输入');
        }

        if(!$data['vehicle_brand']){
            return array('state'=>0,'errormsg'=>'请输入车辆品牌');
        }
//        if(!$data['driving_card']){
//            return array('state'=>0,'errormsg'=>'请上传行驶证');
//        }
        if(isset($data['vin']{16})&&!isset($data['vin']{17})){
            return ['state'=>0,'errormsg'=>'输入错误,vin为17位'];
        }
        //判断vin是否存在
        $res = db('maintain_customer')->where("vin = '$data[vin]'")->find();
        if($res) return array('state'=>0,'errormsg'=>'该Vin号已绑定');

        $where = "user_id = $this->userId and state = 1";
        $tel = db('user_tel')->field('tel')->where($where)->find();
        if($tel){
            $data['pnum'] = $tel['tel'];
        }
        $data['user_id'] = $this->userId;
        $data['state']   = 1;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $res = Db::name('maintain_customer')->insertGetId($data);
        //判断是否是红岩车
//        $info = db('maintain_zvehicle')->where("vhvin = $data[vin]")->find();
//        if(!$info){
//            db('maintain_customer')->where("customer_id = $res")->update(['state'=>2]);
//            return array('state'=>0,'errormsg'=>'您的车不属于红岩车,请等待管理员审核');
//        }
        if($res){
            model('action')->add('添加车辆', '车辆vin号', $data['vin']);
            return array('state'=>1,'customer_id'=>$res);

        }
        return array('state'=>0,'errormsg'=>'new car create false');
    }
    //删除车辆信息
    function vehicle_remove($car_id){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        $where = "customer_id = $car_id";
        $data = [
            'state'=>0
        ];
        $res = db('maintain_customer')->where($where)->update($data);
        if($res){
            $name = db('maintain_customer')->where($where)->find();
            model('action')->add('删除车辆', '车辆vin号', $name['vin']);
            return array('state'=>1,'errormsg'=>'删除成功');
        }
        return array('state'=>0,'errormsg'=>'删除失败');
    }
    //编辑绑定车辆信息
    function vehicle_modify($customer_id,$data){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        if(!$data['vin']){
            return array('state'=>0,'errormsg'=>'请输入vin号');
        }
        if(!$data['uname']){
            return array('state'=>0,'errormsg'=>'请输入驾驶人员姓名');
        }
        if(!$data['role']){
            return array('state'=>0,'errormsg'=>'请选择角色');
        }
        if(!preg_match('/^([\xe4-\xe9][\x80-\xbf]{2}){2,4}$/',$data['uname'])){
            return array('state'=>0,'errormsg'=>'姓名有误,请重新输入');
        }
        if(!$data['vehicle_license_province']){
            return array('state'=>0,'errormsg'=>'请输入车辆所属地');
        }
        if(!$data['vehicle_license_number']){
            return array('state'=>0,'errormsg'=>'请输入车牌号');
        }
        if (!preg_match("/[A-Z][A-Z_0-9]{5}$/", $data['vehicle_license_number'])) {
            return array('state'=>0,'errormsg'=>'车牌号有误,请重新输入');
        }

        if(!$data['vehicle_brand']){
            return array('state'=>0,'errormsg'=>'请输入车辆品牌');
        }
//        if(!$data['driving_card']){
//            return array('state'=>0,'errormsg'=>'请上传行驶证');
//        }
        if(isset($data['vin']{16})&&!isset($data['vin']{17})){
            return ['state'=>0,'errormsg'=>'输入错误,vin为17位'];
        }
        $data['state']   = 1;
        $res = Db::name('maintain_customer')->where("$customer_id = customer_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
        model('action')->add('修改车辆', '车辆vin号', $data['vin']);
        return ['state'=>1,'errormsg'=>'修改成功'];
    }
    //根据vin获取车辆信息
    public function vehicle_info($id)
    {
        if(!$id) return ['state'=>0,'errormsg'=>'请选择车辆'];
        $info = \db('maintain_customer')->where("customer_id = $id and state != 0")->find();
        if(!$info) return ['state'=>0,'errormsg'=>'未找到该车辆'];
        return ['state'=>1,'data'=>['info'=>$info]];
    }
    /* //用户查看预约详情
     function info(){
         $user_id = $this->userId;
         if(!$user_id){
             return [
                 'state'=>0,
                 'errormsg'=>"please login"
             ];
         }
         $where ="user_id=$user_id and state!=0";//1为接受，2为处理中
         $res = Db::name('maintain_apply')->where($where)->find();
         if($res){
             return [
                 'state'=>1,
                 'data'=>['info'=>$res]
             ];
         }
         return [
             'state'=>0,
             'errormsg'=>'not find'
         ];
     }*/
    //用户查看自己的预约列表
    /*function getList($page=null,$maxPerPage=null){
        $user_id = $this->userId;
        if(!$user_id){
            return [
                'state'=>0,
                'errormsg'=>"please login"
            ];
        }
        $where ="user_id=$user_id and state!=0";//不接受为0,1为接受，2为处理中
        $list= Db::name('maintain_apply')->where($where)->limit($page * $maxPerPage, $maxPerPage)->select();
        if($list){
            return [
                'state'=>1,
                'data'=>['info'=>$list]
            ];
        }
        return [
            'state'=>0,
            'errormsg'=>'not find'
        ];
    }*/




    //订单管理
    function order_create(){

    }
    //用户的订单列表
    function order_list($filter){
        if(!$this->userId){
            return array('state'=>0,'errormsg'=>'please login');
        }
        if (isset($filter['page']) && $filter['page'] != '') {
            $page = $filter['page'] - 1;
        } else {
            $page = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }

    }
    //用户获取订单信息
    function order_info($order_id){}
    //管理员查看订单列表
    function order_adminlist($filter){
        if(!$this->auth){
            return array('state'=>0, 'errormsg'=>"No permission");
        }
        if (isset($filter['page']) && $filter['page'] != '') {
            $page = $filter['page'] - 1;
        } else {
            $page = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
    }


    //管理员查看评价列表
    /* function comment_list($filter){
         if(!$this->auth){
             return [
                 'state'=>0,
                 'errormsg'=>"No permission"
             ];
         }
     }*/
    //管理员查看预约列表
    function getList($filter){
        if(!$this->auth){
            return [
                'state'=>0,
                'errormsg'=>"No permission"
            ];
        }
        if (isset($filter['page']) && $filter['page'] != '') {
            $page = $filter['page'] - 1;
        } else {
            $page = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        $where = "state!=0";
        $order = "state desc";
        $list  = Db::name('maintain_apply')
            ->alias('a')
            ->join('maintain_customer b','a.customer_id = b.customer_id')
            ->field('a.*,b.vin')
            ->where($where)
            ->order($order)
            ->limit($page * $maxPerPage, $maxPerPage)
            ->select();
        $class = getConfig('maintain');
        foreach($list as $k=>$v){
            if($v['vin']){
                $where ="vin=".$v['vin'];
                $car_name = Db::name('maintain_zvehicle')->field('zsdcmc')->where($where)->find();
                if($car_name){
                    $list[$k]['car_name'] = $car_name['zsdcmc'];
                }
            }
            foreach($class as $kk=>$vv){
                if($v['type'] == $vv['id']){
                    $list[$k]['types'] = $vv['title'];
                }
            }
        }
        if(!$list){
            return array('state'=>0,'errormsg'=>'not find apply');
        }
        return array('state'=>1,'data'=>['list'=>$list]);

    }

    //合并配件信息
    function merge_parts(){
        set_time_limit(0);
//        try{
//            $statr = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/_hongyanche/parts.txt');
//            if(!$statr){
//                die();
//            }
        //取出配件信息
        //判断条数
        $count = db('maintain_pjprice')->count();
        $page =  ceil($count/5000);
        //取出mall信息
        $mall_list = db('mall')->field('sap_spare_parts_code,mall_id,state')->where('state !=0 and sap_spare_parts_code is not null')->select();
        $time = time();
        if(!$mall_list){
            for($i=1;$i<=$page;$i++) {
                $list = [];
                $pjprice_list = db('maintain_pjprice')->page($i,5000)->select();
                foreach ($pjprice_list as $k => $v) {
                    if ($v['is_sale'] == 1) {
                        $list[$k]['state'] = 1;
                    } else {
                        $list[$k]['state'] = 2;
                    }
                    $list[$k]['name'] = $v['spare_parts_name'];
                    $list[$k]['price'] = (int)($v['uniform_price2'] * 100);
                    $list[$k]['sap_spare_parts_code'] = $v['sap_spare_parts_code'];
                    $list[$k]['spare_parts_code'] = $v['spare_parts_code'];
                    $list[$k]['labels'] = 35;
                    $list[$k]['create_time'] = $time;
                }
                if($list){
                    $res = db('mall')->insertAll($list);
                    sleep(2);
                }else{
                    sleep(2);
                    continue;
                }
                //添加进mall
                //查出id号
                $mall = \db('mall')->field('mall_id,sap_spare_parts_code,state')->where("create_time = $time and state !=0 and sap_spare_parts_code is not null")->select();
                foreach ($mall as $k =>$v){
                    foreach ($list as $kk =>$vv){
                        if($v['sap_spare_parts_code'] == $vv['sap_spare_parts_code']){
                            unset($list[$kk]['state']);
                            unset($list[$kk]['name']);
                            $list[$kk]['mall_id'] = $v['mall_id'];
                            if($v['state'] == 1){
                                $list[$kk]['state'] = 1;
                            }else{
                                $list[$kk]['state'] = 2;
                            }
                        }
                    }
                }
                if($list){
                    $detail = \db('mall_detail')->insertAll($list);
                    sleep(2);
                }else{
                    sleep(2);
                    continue;
                }
            }
            $time = date('Y-m-d H:i:d',time());
            file_put_contents($_SERVER['DOCUMENT_ROOT'].'/_hongyanche/parts.txt',$time.'   第一次导入');
//            sleep(86400);
//            $this->merge_parts();
            die;
        }

        //添加数据
        $sql = "select count(*) as count FROM hy_maintain_pjprice LEFT JOIN (select sap_spare_parts_code as s from hy_mall) as t1 ON hy_maintain_pjprice.sap_spare_parts_code=t1.s where t1.s IS NULL";
        $count = db()->query($sql)[0]['count'];
        $page = ceil($count/3000);
        for($i=0;$i<=$page;$i++) {
            $list2 = [];
            $p = $i*3000;
            $sql = "select * FROM hy_maintain_pjprice LEFT JOIN (select sap_spare_parts_code as s from hy_mall) as t1 ON hy_maintain_pjprice.sap_spare_parts_code=t1.s where t1.s IS NULL LIMIT $p,3000";
            $pjprice_list = db()->query($sql);
            if (!$pjprice_list) {
                sleep(2);
                continue;
            }
            foreach ($pjprice_list as $k => $v) {
                $list2[$k]['name'] = $v['spare_parts_name'];
                $list2[$k]['price'] = (int)($v['uniform_price2'] * 100);
                $list2[$k]['sap_spare_parts_code'] = $v['sap_spare_parts_code'];
                $list2[$k]['spare_parts_code'] = $v['spare_parts_code'];
                $list2[$k]['labels'] = 35;
                $list2[$k]['create_time'] = $time;
                if ($v['is_sale'] == 1) {
                    $list2[$k]['state'] = 1;
                } else {
                    $list2[$k]['state'] = 2;
                }
                $sap_spare_parts_codes[] = $v['sap_spare_parts_code'];
            }
            if ($list2) {
                $res = db('mall')->insertAll($list2);
                sleep(2);
            } else {
                sleep(2);
                continue;
            }
            //添加进mall
            $sap_spare_parts_codes = implode(',', $sap_spare_parts_codes);
//            查出id号
            $mall = \db('mall')->field('mall_id,sap_spare_parts_code,state')->where("create_time = $time")->where("sap_spare_parts_code", 'in', $sap_spare_parts_codes)->select();
            foreach ($mall as $k => $v) {
                foreach ($list2 as $kk => $vv) {
                    if ($v['sap_spare_parts_code'] == $vv['sap_spare_parts_code']) {
                        unset($list2[$kk]['name']);
                        $list2[$kk]['mall_id'] = $v['mall_id'];
                        $list2[$kk]['state'] = $v['state'];
                    }
                }
            }
            if ($list2) {
                $list2 = more_array_unique($list2);
                $detail = \db('mall_detail')->insertAll($list2);
                sleep(2);
            } else {
                sleep(2);
                continue;
            }
            sleep(2);
        }
        //更新数据
        $count = db('maintain_pjprice')
            ->alias('o')
            ->join('mall m','o.sap_spare_parts_code = m.sap_spare_parts_code')
            ->where("state !=0 and m.sap_spare_parts_code is not null")
            ->count();
        $page = ceil($count/3000);
        for($i=1;$i<=$page;$i++) {
            $list3 = [];
            $pjprice_inlist = db('maintain_pjprice')
                ->alias('o')
                ->join('mall m','o.sap_spare_parts_code = m.sap_spare_parts_code')
                ->join('mall_detail d','d.mall_id = m.mall_id')
                ->field('o.spare_parts_name,o.uniform_price2,m.mall_id,detail_id')
                ->where("m.state !=0 and m.sap_spare_parts_code is not null")
                ->page($i,3000)
                ->select();
            if (!$pjprice_inlist) {
                sleep(2);
                continue;
            }
            $detail = [];
            $detail_ids = [];
            foreach ($pjprice_inlist as $k => $v) {
                $list3[$k]['name'] = $v['spare_parts_name'];
                $detail[$k]['price'] = (int)($v['uniform_price2'] * 100);
//                $list3[$k]['sap_spare_parts_code'] = $v['sap_spare_parts_code'];
//                $list3[$k]['spare_parts_code'] = $v['spare_parts_code'];
//                $list3[$k]['labels'] = 35;
                $list3[$k]['create_time'] = $time;
//                $list3[$k]['state'] = $v['state'];
                $list3[$k]['mall_id'] = $v['mall_id'];
                $detail[$k]['detail_id'] = $v['detail_id'];
                $detail_ids[] = $v['detail_id'];
            }
            if ($detail) {
                $this->name = 'mall';
                $this->tabel = 'mall';
                $this->isUpdate(true)->saveAll($list3);
                sleep(2);

                $detail_ids = implode(',',$detail_ids);
                $sql = "UPDATE hy_mall_detail SET price = CASE detail_id ";
                foreach ($detail as $k =>$v){
                    $sql .= sprintf("WHEN %d THEN %d ", $v['detail_id'], $v['price']);
                }
                $sql .= "END WHERE detail_id IN ($detail_ids)";
                db()->query($sql);
//                $this->isUpdate(true)->saveAll($detail);
                sleep(2);
            } else{
                sleep(2);
                continue;
            }
            sleep(2);
        }
        $time = date('Y-m-d H:i:d',time());
        file_put_contents($_SERVER['DOCUMENT_ROOT'].'/_hongyanche/parts.txt',$time.'  合并');
//        sleep(86400);
//        $this->merge_parts();
        die;
//        }
//        catch (\Exception $e){
//            //获取所有系统管理员
//            $config = getConfig('admin_chief');
//            $user_id = implode(',',$config);
//            $message['title'] = '系统消息';
//            $message['other'] = "配件合并接口失效,请重新开启";
//            model('message')->send('maintain',$message,$user_id);
//        }
    }
    //合并配件网点信息
    public function merge_cust()
    {
        set_time_limit(0);
//        try{
//            $statr = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/_hongyanche/cust.txt');
//            if(!$statr){
//                die();
//            }
        //查询出所有网店
        $cust = db('maintain_pj_cust_info')->where("valid_flag = '01' and (cust_type = '03' or cust_type = '07')")->select();
        if(!$cust)  return;
        //查询出所有重卡汇平台网店
        $zcust = db('maintain_pj_cust')->where("state !=0")->select();
        $updata = [];
        if(!$zcust){
            foreach ($cust as $k =>$v){
                $cust[$k] = array_change_key_case($v);
                $cust[$k]['cust_code'] = 'SPM'.$v['cust_code'];
//                if($v['valid_flag'] == '01'){
//                    $cust[$k]['state'] = 1;
//                }else{
                $cust[$k]['state'] = 2;
//                }
                $cust[$k]['create_time'] = time();
            }
            if($cust){
                $res = \db('maintain_pj_cust')->insertAll($cust);
            }else{
//                    sleep(86400);
//                    $this->merge_cust();
            }
            $time = date('Y-m-d H:i:d',time());
            file_put_contents($_SERVER['DOCUMENT_ROOT'].'/_hongyanche/cust.txt',$time.'     第一次导入');
            die;
        }else{
            foreach ($cust as $k =>$v){
                $cust[$k] = array_change_key_case($v);
                $cust[$k]['cust_code'] = 'SPM'.$v['cust_code'];
                $cust[$k]['create_time'] = time();
//                if($v['valid_flag'] == '01'){
//                    $cust[$k]['state'] = 1;
//                }else{
                $cust[$k]['state'] = 2;
//                }
                foreach ($zcust as $kk =>$vv){
                    if($v['cust_code'] == $vv['cust_code']){
                        if(isset($cust[$k])){
                            if($vv['state'] == 1){
                                $cust[$k]['state'] = 1;
                            }else{
                                $cust[$k]['state'] = 2;
                            }
                            $updata[] = $cust[$k];
                            unset($cust[$k]);
                        }
                    }
                }
            }
            if($updata){
                $updata = more_array_unique($updata);
                $res = model('maintain_pj_cust')->saveAll($updata);
                sleep(2);
            }
            if($cust){
                $cust = more_array_unique($cust);
                $res = \db('maintain_pj_cust')->insertAll($cust);
            }
//                sleep(86400);
//                $this->merge_cust();
        }
        $time = date('Y-m-d H:i:d',time());
        file_put_contents($_SERVER['DOCUMENT_ROOT'].'/_hongyanche/cust.txt',$time.'    合并');
//            sleep(86400);
//            $this->merge_cust();
        die;
//        }catch (\Exception $e){
//            //获取所有系统管理员
//            $config = getConfig('admin_chief');
//            $user_id = implode(',',$config);
//            $message['title'] = '系统消息';
//            $message['other'] = "经销商合并接口失效,请重新开启";
//            model('message')->send('maintain',$message,$user_id);
//        }
    }

    //获取车辆轨迹
    public function getTrace($data)
    {
        if(!$data['vhcle']) return ['state'=>0,'errormsg'=>'请选择车辆'];
        $start = date('Y-m-d H:i:s',time()-86400*2);
        $end = date('Y-m-d H:i:s',time());
        if(!is_numeric($data['start'])) return ['state'=>0,'errormsg'=>'时间格式错误'];
        if(!is_numeric($data['end'])) return ['state'=>0,'errormsg'=>'时间格式错误'];
        if($data['start']>$data['end']) return ['state'=>0,'errormsg'=>'结束时间不能大于开始时间'];
        if($data['start']){
            $start = date('Y-m-d H:i:s',$data['start']);
        }
        if($data['end']){
            $end = date('Y-m-isd H:i:s',$data['end']);
        }
        $start = '2017-7-20 12:12:12';
        $end='2017-7-22 12:12:12';
        $start = str_replace(' ','%20',$start);
        $end = str_replace(' ','%20',$end);
//        http://10.86.65.140:8080/pubapi/vehicle/v1/get?vhvin8=GD321068&key=837f373a-23ac-4607-a2f5-b029084841af
//        $res = httpGet("http://10.86.65.140:8080/pubapi/vehicle/v1/trace?vhcle=$data[vhcle]&start=$start&end=$end&key=$this->key");
        $res = '{"message":"success","extend":{"trace":["gpsDate=2017-07-21 19:05:58  longitude=106.508734  latitude=29.544132","gpsDate=2017-07-20 19:05:58  longitude=116.469896  latitude=23.267962","gpsDate=2017-07-20 19:05:58  longitude=116.469896  latitude=23.267962"]}}';
        if(!$res)return ['state'=>0,'errormsg'=>'数据错误'];
        $res = json_decode($res,1);
        if(!$res) return ['state'=>0,'errormsg'=>'数据错误'];
        if($res['message'] !=='success') return ['state'=>0,'errormsg'=>'未找到该信息'];
        if(!isset($res['extend']['trace'])) return ['state'=>0,'errormsg'=>'未找到该信息'];

        $a = [];
        foreach ($res['extend']['trace'] as $k =>$v){
            $a[] = explode('  ',$v);
        }
        foreach ($a as $k =>$v){
            foreach ($v as $kk =>$vv){
                $num = strpos($vv,'=');
                $a[$k][$kk] = substr($vv,$num+1);
            }
        }
        $a = more_array_unique($a);
        foreach ($a as $kkk =>$vvv){
            $a[$kkk][0] = strtotime($vvv[0]);
        }
        //获取地址
        array_multisort(array_column($a,0),SORT_ASC,$a);
        foreach ($a as $k =>$v){
            if(is_array($v)){
                $lng = $v[1];
                $lat = $v[2];
//                $api = "http://api.map.baidu.com/geocoder/v2/?location=".$lat.','.$lng."&output=json&pois=1&ak=zInrkldrOGmWFcCTSifNBRYfKCDtz199";
                //坐标转换
                $api = "http://api.map.baidu.com/geoconv/v1/?coords=".$lng.','.$lat."&from=1&to=5&ak=zInrkldrOGmWFcCTSifNBRYfKCDtz199";
                $address = httpGet($api);
                $address = json_decode($address,1);
                if($address['status'] == 0){
//                    $a[$k]['formatted_address'] = $address['result']['formatted_address'];
//                    $a[$k]['formatted_address'] = '重庆市渝北区宝圣大道两江中学';
//                    $a[$k]['province'] = $address['result']['addressComponent']['province'];
                    $a[$k][1] = $address['result'][0]['x'];
                    $a[$k][2] = $address['result'][0]['y'];
                }
            }
        }
        return ['state'=>1,'data'=>['list'=>$a]];
    }
    //获取车辆位置
    public function getLocate($data)
    {
        if(!$data['vhcle']) return ['state'=>0,'errormsg'=>'请选择车辆'];
//        echo $data['vhcle'];
//        $url = "http://10.86.65.140:8080/pubapi/vehicle/v1/locate?vhcle=$data[vhcle]&key=$this->key";
//        $res = httpGet($url);
        $res = '{"message":"success","extend":{"location":{"province":["广东"],"city":["汕头"]}}}';
        if(!$res)return ['state'=>0,'errormsg'=>'数据错误'];
        $res = json_decode($res,1);
        if($res['message'] !=='success') return ['state'=>0,'errormsg'=>'未找到该信息'];
        $address['address'] = null;
        foreach ($res['extend']['location'] as $k =>$v){
            foreach ($v as $kk =>$vv){
                $address['address'] ? $address['address'] .= $vv : $address['address'] = $vv;
            }
        }
        return ['state'=>1,'data'=>['info'=>$address]];
    }
    //获取车辆信息
    public function getCarInfo($data)
    {
        if(!$data['vhcle']) return ['state'=>0,'errormsg'=>'请选择车辆'];
        $data['start'] = strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y'))));
        $data['end'] = strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1));
        $data['vhcle'] = substr($data['vhcle'],-8);
//        $res = httpGet("http://10.86.65.140:8080/pubapi/vehicle/v1/get?vhvin8=$data[vhcle]&key=837f373a-23ac-4607-a2f5-b029084841af");
        $res = '{"message":"success","extend":{"vehicle":{"vhcle":"0070231880","vhvin":null,"vhvin8":"GD321068","deviceNo":"64696253987","simNo":"64696253987","license":null}}}';
        if(!$res) {
            return ['state'=>0,'errormsg'=>'数据错误','ss'=>1];
        }
        $res = json_decode($res,1);
        if($res['message'] !=='success') return ['state'=>0,'errormsg'=>'未找到该信息'];
        $info = $res['extend']['vehicle'];
        if($info['vhvin']){
            $info['vhvin'] = substr_replace($info['vhvin'],'****',0,13);
        }
        //修改vhcle
        db('maintain_customer')->where("vin like '%$info[vhvin8]%' and user_id = $this->userId")->update(['vhcle'=>$info['vhcle']]);
        $data['vhcle'] = $info['vhcle'];
        //获取车辆里程油耗
        $a = true;
        $i = 1;
        while ($a){
            $conusm = $this->getConsumption($data,1);
            $i++;
            if($conusm['state']) {
                $a = false;
            }elseif($i>3){
                return ['state'=>0,'errormsg'=>'数据错误','ss'=>2];
                $a = false;
            }

        }
        if($conusm['state']){
            if($conusm['data']['info'])
            {
                $info = array_merge($info,$conusm['data']['info']);
            }
        }
        $b = true;
        $i = 1;
        while ($b){
            $address = $this->getLocate($data);
            $i++;
            if($address['state']) {
                $b = false;
            }elseif($i>3){
                return ['state'=>0,'errormsg'=>'数据错误','ss'=>3];
                $b = false;
            }

        }
        //获取车 当前位置
        if($address['state']){
            if($address['data']['info'])
            {
                $info = array_merge($info,$address['data']['info']);
            }
        }
//        dump($info);
//        unset($info['vhcle']);
        return ['state'=>1,'data'=>['info'=>$info]];
    }
    //车辆里程油耗
    public function getConsumption($data,$is = null)
    {
        if(!$data['vhcle']) return ['state'=>0,'errormsg'=>'请选择车辆'];
        if($is){
            $start = date('Y-m-d H:i:s',time()-86400*2);
            $end = date('Y-m-d H:i:s',time());
            $start = '2017-7-20 00:00:00';
            $end='2017-7-21 00:00:00';
            $start = str_replace(' ','%20',$start);
            $end = str_replace(' ','%20',$end);
//            $url = "http://10.86.65.140:8080/pubapi/vehicle/v1/consumption?vhcle=0070231880&start=$start&end=$end&key=$this->key";
//            $res = httpGet($url);
            $res = '{"message":"success","extend":{"consumption":{"date":"2017-07-21","fuelConsumption":100,"mileage":111,"lp100km":20,"totalFuelConsumption":22091.0,"totalMileage":371235.0}}}';
            if(!$res) return ['state'=>0,'errormsg'=>'数据错误'];
            $res = json_decode($res,1);
            if($res['message'] !=='success') return ['state'=>0,'errormsg'=>'未找到该信息'];
            $info = $res['extend']['consumption'];
            return ['state'=>1,'data'=>['info'=>$info]];
        }
        $start = time()-86400*7;
//        $start = time()-86400*2;
//        $end = time();
        $end = time();
//        if($data['start']){
//            $start =$data['start'];
//        }
//        if($data['end']){
//            $end = $data['end'];
//        }
//        if($start>$end) return ['state'=>0,'errormsg'=>'结束时间不能大于开始时间'];
//        if($end - $start > 86400*7) return ['state'=>0,'errormsg'=>'时间不能大于七天'];
        $a = true;
        $res = [];
        while ($a){
            $ends = $start +(86400*2);
            if($ends > $end){
                $ends = $end;
                $a = false;
            }
            $s = date('Y-m-d%20H:i:s',$start);
            $e = date('Y-m-d%20H:i:s',$end);
            //调接口
            $res[] = httpGet("http://hy.tiesh.com/test/test7");
            // $res = httpGet("http://10.86.65.140:8080/pubapi/vehicle/v1/consumption?vhcle=$data[vhcle]&start=$s&end=$e&key=$this->key");
            $start = $ends;

        }
        if(!$res) return ['state'=>0,'errormsg'=>'数据错误'];
        $list = [];
        $info = [];
        foreach ($res as $k_k =>$v_v){
            $ress = json_decode($v_v,1);
            if($ress['message'] !=='success') return ['state'=>0,'errormsg'=>'未找到该信息'];
            $info = $info ? array_merge($info,$ress['extend']['consumption']): $ress['extend']['consumption'];
        }
        foreach ($info as $k =>$v){
            foreach ($v as $kk=>$vv){
                $list[$kk][] = $vv;
            }
        }
        return ['state'=>1,'data'=>['list'=>$list,'list2'=>$info]];

    }
    //
}